<template>
  <div class="full-box">
    <el-row>
      <div class="title-box">
        <el-text class="title">下单</el-text>
      </div>
    </el-row>
    <el-row class="searchAreaProduct">
      <el-form label-width="150px" style="width: 100%">
        <el-row>
          <el-col :span="8">
            <el-form-item label="通用名">
              <el-input v-model="data.product.nickName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品名">
              <el-input v-model="data.product.productName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商">
              <el-input v-model="data.product.suppliers">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品批号">
              <el-select v-model="data.product.classs" placeholder="全部批号">
                <el-option v-for="classs in data.classes" :label="classs.descs" :value="classs.descs">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剂型">
              <el-select v-model="data.product.type" placeholder="全部剂型">
                <el-option v-for="type in data.types" :label="type.descs" :value="type.descs">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="">
              <el-button @click="query" type="success" style="width: 350px">
                <el-icon>
                  <Search/>
                </el-icon>&nbsp;&nbsp;搜索
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <el-row class="buttonGroup">
      <el-button-group>
        <el-button type="warning" @click="insertNewOrder">
          <el-icon>
            <CircleCheck/>
          </el-icon>
          &nbsp
          结算
        </el-button>
      </el-button-group>
    </el-row>
    <el-row class="table">
      <el-table
          :row-key="row => row.productId"
          :data="data.productList"
          @selection-change="handleSelectionChange">
        <el-table-column
            :reserve-selection="true"
            type="selection"></el-table-column>
        <el-table-column prop="nickName" label="通用名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="productName" label="商品名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit" label="包装规格" width="150px"></el-table-column>
        <el-table-column prop="suppliers" label="生产厂家" width="200px" show-overflow-tooltip></el-table-column>
        <el-table-column prop="classs" label="产品批号" width="150px"></el-table-column>
        <el-table-column prop="type" label="剂型"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column label="购买数量" width="200px" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.num" :min="0" size="small">
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="width: 100%; display: flex;justify-content: right">
        <el-pagination
            style="margin-top: 10px"
            v-model:current-page="data.stockPage.currentPage"
            @current-change="handleCurrentChangeStock"
            layout="prev, pager, next"
            :page-size="5"
            :total="data.stockPage.total"
        />
      </el-row>
    </el-row>


  </div>
  <!--添加对话框-->
  <el-dialog v-model="data.orderDialog.show" title="添加新订单" style="width: 600px">
    <el-form label-width="120px">
      <el-form-item label="客户名">
        <el-input style="width: 240px" v-model="data.order.client"></el-input>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input style="width: 240px" v-model="data.order.consignee"></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input style="width: 240px" v-model="data.order.consigneePhone"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input style="width: 240px" v-model="data.order.address"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.orderDialog.show = false">取消</el-button>
        <el-button type="primary" @click="orderCertain">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, onMounted, ref} from "vue";
import axios from "axios";
import moment from "moment";
import router from "@/router";
import {ElMessage} from "element-plus";

// 定义一个接口来表示订单详情的结构
interface OrderDetail {
  detailId: string;
  orderId: string;
  productId: number;
  quantity: number;
}

//定义产品结构
interface ProductItem {
  productId: number;
  nickName: string;
  productName: string;
  unit: string;
  suppliers: string;
  classId: number;
  typeId: number;
  stockCount: number;
  price: number;
  classs: string;
  type: string;
  num: number;
}

let productList2 = ref<ProductItem[]>([]);

const data = reactive({
  userId: '',
  list: [],
  stockPage: {
    currentPage: 1,
    total: ""
  },
  addProduct: {
    productId: "",
    quantity: ""
  },
  key: "",//要添加商品的orderId
  loading: {
    loadingId: "",
    orderId: "",
    loader: "",
    creTime: "",
    endTime: ""
  },//loading添加信息
  //订单添加数据
  order: {
    orderId: "",
    client: "",
    createTime: moment(new Date()).format(' YYYY-MM-DD HH:mm:ss'),
    deliverTime: moment(new Date()).format(' YYYY-MM-DD HH:mm:ss'),
    consignee: "",
    consigneePhone: "",
    address: "",
    userId: ""
  },
//  订单对话框
  orderDialog: {
    show: false
  },
  //个人信息
  InfoDialog: {
    title: "",
    clientInfo: {
      client: "",
      consignee: "",
      consigneePhone: "",
      address: "",
      userId: ""
    },
    show: false
  },
  productList: [],
  //商品查询
  product: {
    nickName: "",
    productName: "",
    suppliers: "",
    classs: "",
    type: ""
  },
  classes: [],
  types: []
})

//下拉
const initSelect = () => {
  //批号
  axios({
    url: "http://localhost:8080/dict/selectClass",
    method: "get",
    params: ""
  }).then((res) => {
    data.classes = res.data.data;
  })
  //剂型
  axios({
    url: "http://localhost:8080/dict/selectType",
    method: "get",
    params: ""
  }).then((res) => {
    data.types = res.data.data;
  })
}
//商品查询
const query = () => {
  axios({
    url: "http://localhost:8080/productView/myQuery",
    method: "get",
    params:
        {
          currentPage: data.stockPage.currentPage,
          size: 5,
          nickName: data.product.nickName,
          productName: data.product.productName,
          suppliers: data.product.suppliers,
          classs: data.product.classs,
          type: data.product.type
        }
  }).then((res) => {
    data.productList = res.data.data;
    data.stockPage.total = res.data.total;
  })
}

onMounted(() => {
  getId();
  getInfo();
  handleCurrentChangeStock()

  initSelect();
})
//商品表
const handleCurrentChangeStock = () => {
  axios({
    url: "http://localhost:8080/productView/selectAll",
    method: "get",
    params: {
      currentPage: data.stockPage.currentPage,
      size: 5
    }
  }).then((res) => {
    data.productList = res.data.data;
    data.stockPage.total = res.data.total;
  })
}
//获得多选框信息
const handleSelectionChange = (val: ProductItem[]) => {
  console.log(val.length);
  productList2.value = val;
  console.log(productList2);
}

//初始化订单信息
const initOrder = () => {
  data.order.orderId = "";
  data.order.client = data.InfoDialog.clientInfo.client;
  data.order.consignee = data.InfoDialog.clientInfo.consignee;
  data.order.consigneePhone = data.InfoDialog.clientInfo.consigneePhone,
      data.order.address = data.InfoDialog.clientInfo.address,
      data.order.userId = data.userId;
}
//获取userID
const getId = () => {
  console.log(sessionStorage.getItem("userId"));
  const key = sessionStorage.getItem("userId");
  if (key) {
    data.userId = key;
    getInfo();
  } else {
    errorMessage("获取userId失败");
  }
}
//获取个人信息
const getInfo = () => {
  axios({
    url: "http://localhost:8080/clientInfo/getInfo",
    method: "get",
    params: {
      userId: data.userId
    }
  }).then((res) => {
    data.InfoDialog.clientInfo = res.data.data;
  })
}

//添加新订单
let insertNewOrder = () => {
  initOrder();
  data.orderDialog.show = true;
}
//修改订单状态
let setStatus = (orderId: String) => {
  axios({
    url: "http://localhost:8080/deliverOrder/insert",
    method: "post",
    params: {
      orderId: orderId,
      statusId: 31
    }
  })
}
//确认结算
let orderCertain = () => {
  axios({
    url: "http://localhost:8080/Order/createNewOrder",
    method: "post",
    params: data.order
  }).then((res) => {
    if (res.data.success) {
      data.order.orderId = res.data.data.orderId;
      setStatus(res.data.data.orderId);
      certainProduct();
    } else {
      errorMessage(res.data.msg);
    }
  })
  data.orderDialog.show = false;
}
//结算
let certainProduct = () => {
  // 使用接口来声明 orderDetailsList，并指定其元素类型为 OrderDetail
  let orderDetailsList: OrderDetail[] = [];
  for (var i = 0; i < productList2.value.length; i++) {
    const orderDetail = {
      detailId: "",
      orderId: "",
      productId: 0,
      quantity: 0
    }//获取选定商品列表
    orderDetail.orderId = data.order.orderId;
    orderDetail.productId = productList2.value[i].productId;
    orderDetail.quantity = productList2.value[i].num;
    orderDetailsList.push(orderDetail);
  }
  //给订单添加商品
  axios({
    url: "http://localhost:8080/OrderDetails/test", // 只需要资源路径
    method: "post", // 使用POST方法
    data: orderDetailsList
  }).then(response => {
    if (response.data.success) {
      successMessage("创建成功");
      creLoading();
      router.push("/return/clientHome/MyOrder");
    } else {
      deleteOrders(data.order.orderId);
    }
    // 处理响应
    console.log(response.data);
  }).catch(error => {
    // 处理错误
    console.error(error);
  });

}


//删除订单
const deleteOrders = (orderId: string) => {
  axios({
    url: "http://localhost:8080/Order/deleteOrder", // 只需要资源路径
    method: "post", // 使用POST方法,
    params: {orderId: orderId}
  }).then((res) => {
    if (res.data.success) {
      errorMessage(res.data.msg);
    } else {
      errorMessage("删除订单错误");
    }
  })
}
//成功消息
const successMessage = (message: any) => {
  ElMessage({
    showClose: true,
    message: message,
    type: 'success',
  });
}
//失败消息
const errorMessage = (message: any) => {
  ElMessage({
    showClose: true,
    message: message,
    type: 'error',
  });
}
//  创建装配单
const creLoading = () => {
  data.loading.creTime = data.order.createTime;
  data.loading.endTime = moment(new Date()).format(' YYYY-MM-DD HH:mm');
  data.loading.orderId = data.order.orderId;
  axios({
    url: "http://localhost:8080/loading2/save", // 只需要资源路径
    method: "post", // 使用POST方法,
    params: data.loading
  }).then((res) => {
    if (res.data.success) {
    } else {
      errorMessage("创建配送单失败");
    }
  })
}

</script>

<style scoped>
.full-box {
  width: 100%;
  height: 100vh;
}

.table {
  margin-top: 10px;

}

.buttonGroup {

}

.title-box {
  margin-top: 20px;
  width: 100%;
  height: 100px;
  border: 2px rgba(66, 61, 61, 0.89) dashed;
  background: #efedcb;
  border-radius: 30px;
}

.title {
  font-size: 40px;
  color: #6b5614;
  line-height: 100px;
  margin-left: 40px;
}

.searchAreaProduct {

  margin-top: 20px;
  width: 90%;
  margin-bottom: 10px;
}
</style>